package com.lzx.ai.template;

import com.baidu.aip.face.AipFace;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;

/**
 * @author 程序员星星
 * @date 2022/12/17
 * @Description
 */
@Component
public class FaceTemplate {
    @Resource
    private AipFace client;

    /**
     * 检测图片中是否包含人脸
     * true：包含
     * false：不包含
     */
    public boolean detect(String imageUrl) {
        try {
            // 调用接口
            String imageType = "URL";
            // 传入可选参数调用接口
            HashMap<String, Object> options = new HashMap<>();
            options.put("face_field", "age");
            options.put("max_face_num", "2");
            options.put("face_type", "LIVE");
            options.put("liveness_control", "LOW");
            // 人脸检测
            JSONObject res = client.detect(imageUrl, imageType, options);
            Integer error_code = (Integer) res.get("error_code");
            return error_code == 0;
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
    }
}
